Micron Document
Livres et Wikis | Archives | Info


JavaScript syntax
part 11/31 Β· 107.4 KB total
layout: Wide Β· Narrow Β· Centered
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
if (0 || -0 || "" || null || undefined || b.valueOf() || !new Boolean() || !t) {
console.log("Never this");
} else if ([] && {} && b && typeof b === "object" && b.toString() === "false") {
console.log("Always this");
}

Symbol

Symbols are a feature introduced in ES6. Each symbol is guaranteed to be a unique value, and they can be used for encapsulation.cite-ref-15[15]

Example:

let x = Symbol(1);
const y = Symbol(1);
x === y; // => false
const symbolObject = {};
const normalObject = {};
// since x and y are unique,
// they can be used as unique keys in an object
symbolObject[x] = 1;
symbolObject[y] = 2;
symbolObject[x]; // => 1
symbolObject[y]; // => 2
// as compared to normal numeric keys
normalObject[1] = 1;
normalObject[1] = 2; // overrides the value of 1
normalObject[1]; // => 2
// changing the value of x does not change the key stored in the object
x = Symbol(3);
symbolObject[x]; // => undefined
// changing x back just creates another unique Symbol
x = Symbol(1);
symbolObject[x]; // => undefined

There are also well known symbols.

One of which is Symbol.iterator; if something implements Symbol.iterator, it is iterable:

const x = [1, 2, 3, 4]; // x is an Array
x[Symbol.iterator] === Array.prototype[Symbol.iterator]; // and Arrays are iterable
const xIterator = x[Symbol.iterator](); // The [Symbol.iterator] function should provide an iterator for x
xIterator.next(); // { value: 1, done: false }
xIterator.next(); // { value: 2, done: false }
xIterator.next(); // { value: 3, done: false }
xIterator.next(); // { value: 4, done: false }
xIterator.next(); // { value: undefined, done: true }
xIterator.next(); // { value: undefined, done: true }
// for..of loops automatically iterate values
for (const value of x) {
console.log(value); // 1 2 3 4
}
// Sets are also iterable:
[Symbol.iterator] in Set.prototype; // true
for (const value of new Set(['apple', 'orange'])) {
console.log(value); // "apple" "orange"
}


──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────